﻿package com.thorqq.magictimer.timeLoop;

import java.util.Vector;

import android.os.Parcel;
import android.os.Parcelable;

import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.core.TLoopPolicy;
import com.thorqq.magictimer.core.TTimerDef;
import com.thorqq.magictimer.core.TimerAbs;
import com.thorqq.magictimer.core.TimerCalculatorAbs;
import com.thorqq.magictimer.util.DateUtil;
import com.thorqq.magictimer.util.Util;

//原始的定时器数据结构
public class Timer extends TimerAbs
{
//    private TTimerDef mTimerDef;
//    private Vector<TLoopPolicy> mLoopPolicys;
//    private Vector<TAction> mActions;
//    private long mNextTime = -1;
//
//    @Override
//    public String toString()
//    {
//        return mTimerDef.getName() + " : " + DateUtil.MillisToStr(mNextTime) + "("+ mNextTime +")";
//    }
    
    /**
     * 计算下一次启动时间
     * 
     * @return 下一次启动时间，毫秒
     */
    public long calculate(long nowInMillis)
    {
        Util.log("Calculate " + getName());
        TimerCalculatorAbs tc = new TimerCalculator(nowInMillis);

        tc.setTime(mTimerDef);
        for (TLoopPolicy tlp : mLoopPolicys)
        {
            {
                tc.addLoopPolicy(tlp);
            }
        }
        
        mNextTime = tc.caculate(getTimerDef().getLastAlertTime());
        Util.log(getName() + ": " + DateUtil.MillisToStr(mNextTime));

        return mNextTime;
    }

    public Timer()
    {
        mTimerDef = new TTimerDef();
        mLoopPolicys = new Vector<TLoopPolicy>();
        mActions = new Vector<TAction>();
        mNextTime = -1;
    }

    @SuppressWarnings("unchecked")
    public Timer(Parcel p)
    {
        mNextTime = p.readLong();
        mTimerDef = (TTimerDef)p.readSerializable();
        mLoopPolicys = (Vector<TLoopPolicy>) p.readSerializable();
        mActions = (Vector<TAction>)p.readSerializable();
    }

    public static final Parcelable.Creator<Timer> CREATOR = new Parcelable.Creator<Timer>()
    {
        public Timer createFromParcel(Parcel p)
        {
            return new Timer(p);
        }

        public Timer[] newArray(int size)
        {
            return new Timer[size];
        }
    };

}
